package test;
import java.util.Stack;

public class Calculator {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(calc("( ( 1 + 2 ) * 5 )"));
	}

	public static double calc(String expr) {
		Stack ops = new Stack();
		Stack nums = new Stack();

		String[] parts = expr.split("\\s");
		for (int i = 0, length = parts.length; i < length; i++) {
			String part = parts[i];

			if ("+".equals(part) || "-".equals(part) || "*".equals(part)
					|| "/".equals(part)) {
				ops.push(part);
			} else if (")".equals(part)) {
				double num1 = ((Double) nums.pop()).doubleValue();
				double num2 = ((Double) nums.pop()).doubleValue();
				String op = (String) ops.pop();
				if ("+".equals(op)) {
					num1 += num2;
				} else if ("-".equals(op)) {
					num1 -= num2;
				} else if ("*".equals(op)) {
					num1 *= num2;
				} else {
					num1 /= num2;
				}

				nums.push(new Double(num1));
			} else if(!"(".equals(part)){
				nums.push(new Double(Double.parseDouble(part)));
			}
		}

		return ((Double) nums.pop()).doubleValue();
	}
}
